import cv2
import time


# (640, 480),
# # (800, 600),
# (1024, 768),
# (1280, 720),
# (1280, 1024),
# # (1600, 1200),
# # (1920, 1080),
# # (2560, 1440),
# # (3840, 2160)

FW = 1280
FH = 720


class CameraStream:
    def __init__(self, camera_id):
        self.camera_id = camera_id
        self.cap = cv2.VideoCapture(camera_id)

        # 尝试设置分辨率
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, FW)  
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FH)  

        # 获取实际设置的分辨率
        width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
        height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
        print('------------------------------------')
        print(f"Camera ID: {camera_id}")
        print(f"Requested resolution: {FW}x{FH}")
        print(f"Actual resolution: {width}x{height}")
        print('------------------------------------')
        self.cap.set(cv2.CAP_PROP_FPS, 15)  # 降低帧率


    def get_frame(self):
        ret, frame = self.cap.read()
        if not ret:
            print("Warning: Failed to capture frame")
            return None
        
        # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        return frame



    def __del__(self):
        if self.cap.isOpened():
            self.cap.release()
